﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Text;
using System.Windows.Forms;
using vdxFcnv;
using VectorDraw.Professional.Components;
using VectorDraw.Professional.Constants;
using VectorDraw.Professional.vdFigures;
using VectorDraw.Professional.vdObjects;
using VectorDraw.Professional.vdPrimaries;
using VectorDraw.Render;

namespace ZhCAD
{
    public class DocHelper
    {
        private static Dictionary<string, string> _cassdic;

        private static vdDocument CreateDocument()
        {
            var document = new vdDocumentComponent().Document;
            document.GroupGrips = vdDocument.GroupGripsEnum.AllEntities;
            document.EnableAutoFocus = true; //自动获取焦点
            document.GlobalRenderProperties.SelectionPreview = vdRenderGlobalProperties.SelectionPreviewFlags.ON;
            document.GlobalRenderProperties.SelectionPreviewColor = Color.Gold;
            document.SupportPath = Application.StartupPath + "\\System";
            //Document.EnableAutoFocus = true;
            return document;
        }



        private static void OpenDocument(vdDocument document, string filename)
        {
            //document.OnProgressStart += Document_OnProgressStart;
            document.OnProgress += Document_OnProgress;

            ConversionUtilities.OpenDwg(document, filename);
            //document.OnProgressStart -= Document_OnProgressStart;
            document.OnProgress -= Document_OnProgress;
  
        }



        private static void Document_OnProgressStart(object sender, string jobDescription, long meterLimit)
        {
            MyEvent(sender, 0, jobDescription);
        }

        private static void Document_OnProgress(object sender, long percent, string jobDescription)
        {
            MyEvent(sender, percent, jobDescription);
        }

        public delegate void MyEventHandle(object sender, long percent, string jobDescription);

        public static event MyEventHandle MyEvent;

        internal static vdDocument OpenDocument(string[] files, FileTree filelList)
        {
            var document = CreateDocument();
            if (files.Length == 0)
            {
                OpenDocument(document, "", filelList);
            }
            else
            {
                OpenDocument(document, files[0], filelList);
                for (var i = 1; i < files.Length; i++)
                {
                    var filename = files[i];
                    var newdoc = CreateDocument();
                     OpenDocument(newdoc,filename);
                    var curcount = document.Model.Entities.Count;
                    MergeFile(document, newdoc);

                    GetFileTree(document, filename, filelList, curcount);
                   
                }
            }
            document.ZoomExtents();
            return document;
        }

        internal static void OpenDocument(vdDocument document, string file, FileTree filetree)
        {
            if (file != "") OpenDocument(document, file);
            GetFileTree(document, file, filetree);
   
        }

        internal static void DeleteEntFormFileTree(int id, FileTree fileTree)
        {
    
                //foreach (var treeLayer in fileTree.)
                //{
                //    var feature = treeLayer.Value.Entites.Find(x => x.Id == id);
                //    if (feature != null)
                //    {
                //        treeLayer.Value.Entites.Remove(feature);
                //        return;
                //    }
                //}
        }

        //internal static void AddEntToFileTree(vdFigure ent, List<FileTree> fileTrees, string filename)
        //{
        //    var filetree =
        //        fileTrees.Find(x => x.Filename.Equals(filename, StringComparison.CurrentCultureIgnoreCase));

        //    AddEntToFileTree(ent, filetree);
        //}

        internal static void AddEntToFileTree(string filename,vdFigure ent, FileTree fileTree)
        {
            var entType = EntType.Point;
            switch (ent._TypeName)
            {
                case "vdText":
                    entType = EntType.Text;
                    break;

                case "vdLine":
                    entType = EntType.Polyline;
                    break;
                case "vdPolyline":
                    var polyline = (vdPolyline) ent;

                    if (polyline.Flag == VdConstPlineFlag.PlFlagCLOSE)
                        entType = EntType.Polygon;
                    else
                        entType = EntType.Polyline;
                    break;
                case "vdPoint":
                case "vdInsert":
                    entType = EntType.Point;
                    break;
            }

            var vp = ent.XProperties.FindName("SOUTH");
            var casscode = "";
            if (vp != null)
                casscode = vp.PropValue.ToString();
            fileTree.AddEnt(filename,new Feature
            {
                Id = ent.Id,
                Cass = casscode,
                //CassDesc = GetCassDesc(casscode),
                EntType = entType,
                Handle = ent.Handle.Value,
                Layer = ent.Layer.Name
            });
        }

        public static string GetCassDesc(string casscode)
        {
            if (_cassdic == null)
            {
                _cassdic = new Dictionary<string, string>();
                var allLn = File.ReadAllLines(Application.StartupPath + "\\system\\index.ini", Encoding.Default);
                foreach (var s in allLn)
                {
                    var sv = s.Split(',');
                    if (sv.Length >= 4)
                        _cassdic[sv[0]] = sv[3];
                }
            }
            _cassdic.TryGetValue(casscode, out var result);
            return result;
        }

        internal static void GetFileTree(vdDocument document,string filename, FileTree fileTree, int start = 0)
        {
            foreach (vdLayer layer in document.Layers)
                fileTree.AddLayer( new MLayer
                {
                    LayerName = layer.Name,
                   
                    Color = layer.PenColor.SystemColor
                });


            for (var i = start; i < document.Model.Entities.Count; i++)
            {
                var ent = document.Model.Entities[i];
                AddEntToFileTree(filename,ent, fileTree);
            }
        }

        private static void MergeFile(vdDocument doc, vdDocument doc1)
        {
            doc.MergeTables(doc1, false, false);

            //先复制编组要素
            foreach (vdGroup grp1 in doc1.Groups)
            {
                var grpp = doc.Groups.FindName(grp1.Name);
                if (grpp == null)
                {
                    var prigrp = grp1.Clone(doc);
                    doc.Groups.Add(prigrp);
                    grpp = (vdGroup) prigrp;
                }
                else
                {
                    grpp = new vdGroup();
                    doc.Groups.Add(grpp);
                }

                CopyGroupEntities(doc, grpp, grp1);
            }


            foreach (vdFigure ent in doc1.Model.Entities)
            {
                var primary = ent.Clone(doc);
                if (!ent.InGroup())
                    doc.Model.Entities.AddItem(primary);
            }
        }


        private static void CopyGroupEntities(vdDocument doc, vdGroup grpp, vdGroup grp1)
        {
            foreach (vdFigure figure in grp1)
            {
                var primary = figure.Clone(doc);
                grpp.AddItem(primary);
                doc.Model.Entities.AddItem(primary);
            }
        }


        public static string[] GetOpenFileNameDlg()
        {
            var dlg = new OpenFileDialog
            {
                Title = "指定要打开的文件",
                FileName = "",
                Filter = "CAD文件|*.dwg;*.dxf;*.dgn",
                Multiselect = true
            };
            if (dlg.ShowDialog() == DialogResult.OK)
                return dlg.FileNames;
            return null;
        }
    }

  
}